/**
 * 自动补全服务
 * 通过WebSocket实现实时智能补全
 */

import type { EditorContext, AutocompleteOption } from '@/stores/copilot.store';

/**
 * 自动补全请求
 */
interface AutocompleteRequest {
  action: 'get_suggestions';
  context: {
    current_text: string;
    cursor_position: number;
    previous_paragraphs: string[];
    word_count: number;
  };
}

/**
 * 自动补全响应
 */
interface AutocompleteResponse {
  type: 'suggestions';
  suggestions: Array<{
    text: string;
    confidence: number;
    type: 'word' | 'sentence' | 'paragraph';
  }>;
}

/**
 * 自动补全服务类
 */
class AutocompleteService {
  private wsConnection: WebSocket | null = null;
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectDelay = 2000;
  private heartbeatInterval: number | null = null;
  private messageHandlers: Array<(data: AutocompleteResponse) => void> = [];

  /**
   * 连接WebSocket
   */
  async connect(): Promise<void> {
    const wsUrl = import.meta.env.VITE_COPILOT_WS_URL || 'ws://localhost:8000/ws/copilot/autocomplete';

    console.log('🔌 [Autocomplete] Connecting to:', wsUrl);

    try {
      this.wsConnection = new WebSocket(wsUrl);

      this.wsConnection.onopen = () => {
        console.log('✅ [Autocomplete] Connected');
        this.reconnectAttempts = 0;
        this.startHeartbeat();
      };

      this.wsConnection.onmessage = (event) => {
        try {
          const data: AutocompleteResponse = JSON.parse(event.data);
          console.log('📨 [Autocomplete] Received:', data.type);

          // 调用所有注册的消息处理器
          this.messageHandlers.forEach((handler) => handler(data));
        } catch (error) {
          console.error('❌ [Autocomplete] Failed to parse message:', error);
        }
      };

      this.wsConnection.onerror = (error) => {
        console.error('❌ [Autocomplete] WebSocket error:', error);
      };

      this.wsConnection.onclose = () => {
        console.log('🔌 [Autocomplete] Connection closed');
        this.stopHeartbeat();
        this.handleReconnect();
      };
    } catch (error) {
      console.error('❌ [Autocomplete] Failed to connect:', error);
      this.handleReconnect();
    }
  }

  /**
   * 断开连接
   */
  disconnect(): void {
    if (this.wsConnection) {
      this.wsConnection.close();
      this.wsConnection = null;
    }
    this.stopHeartbeat();
  }

  /**
   * 重连处理
   */
  private handleReconnect(): void {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('❌ [Autocomplete] Max reconnect attempts reached');
      return;
    }

    this.reconnectAttempts++;
    console.log(`🔄 [Autocomplete] Reconnecting (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);

    setTimeout(() => {
      this.connect();
    }, this.reconnectDelay * this.reconnectAttempts);
  }

  /**
   * 启动心跳
   */
  private startHeartbeat(): void {
    this.heartbeatInterval = window.setInterval(() => {
      if (this.wsConnection && this.wsConnection.readyState === WebSocket.OPEN) {
        this.wsConnection.send(JSON.stringify({ type: 'ping' }));
      }
    }, 30000); // 每30秒发送一次心跳
  }

  /**
   * 停止心跳
   */
  private stopHeartbeat(): void {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
      this.heartbeatInterval = null;
    }
  }

  /**
   * 注册消息处理器
   */
  onMessage(handler: (data: AutocompleteResponse) => void): () => void {
    this.messageHandlers.push(handler);

    // 返回取消注册函数
    return () => {
      this.messageHandlers = this.messageHandlers.filter((h) => h !== handler);
    };
  }

  /**
   * 发送上下文请求补全建议
   */
  sendContext(context: EditorContext): void {
    if (!this.wsConnection || this.wsConnection.readyState !== WebSocket.OPEN) {
      console.warn('⚠️ [Autocomplete] WebSocket not connected, using mock data');
      this.sendMockSuggestions(context);
      return;
    }

    const request: AutocompleteRequest = {
      action: 'get_suggestions',
      context: {
        current_text: context.currentText,
        cursor_position: context.cursorPosition,
        previous_paragraphs: context.previousParagraphs,
        word_count: context.wordCount,
      },
    };

    console.log('📤 [Autocomplete] Sending context');
    this.wsConnection.send(JSON.stringify(request));
  }

  /**
   * 发送Mock建议（WebSocket未连接时使用）
   */
  private sendMockSuggestions(context: EditorContext): void {
    // 模拟延迟
    setTimeout(() => {
      const mockResponse: AutocompleteResponse = {
        type: 'suggestions',
        suggestions: this.generateMockSuggestions(context),
      };

      this.messageHandlers.forEach((handler) => handler(mockResponse));
    }, 500);
  }

  /**
   * 生成Mock补全建议
   */
  private generateMockSuggestions(context: EditorContext): Array<{
    text: string;
    confidence: number;
    type: 'word' | 'sentence' | 'paragraph';
  }> {
    const lastWords = context.currentText.trim().split(/\s+/).slice(-3).join(' ');

    if (lastWords.includes('AI') || lastWords.includes('人工智能')) {
      return [
        {
          text: '技术的发展为内容创作带来了革命性的变化',
          confidence: 0.92,
          type: 'sentence',
        },
        {
          text: '正在改变传统的写作方式和创作流程',
          confidence: 0.88,
          type: 'sentence',
        },
        {
          text: '能够帮助作者提升工作效率',
          confidence: 0.85,
          type: 'sentence',
        },
      ];
    }

    if (lastWords.includes('例如') || lastWords.includes('比如')) {
      return [
        {
          text: '在新闻写作领域，AI可以快速生成新闻稿',
          confidence: 0.90,
          type: 'sentence',
        },
        {
          text: '某科技公司通过AI技术提升了50%的内容产出',
          confidence: 0.87,
          type: 'sentence',
        },
      ];
    }

    return [
      {
        text: '这一趋势正在加速发展',
        confidence: 0.80,
        type: 'sentence',
      },
      {
        text: '带来了深远的影响',
        confidence: 0.75,
        type: 'sentence',
      },
    ];
  }

  /**
   * 检查连接状态
   */
  isConnected(): boolean {
    return this.wsConnection !== null && this.wsConnection.readyState === WebSocket.OPEN;
  }

  /**
   * 获取连接状态
   */
  getConnectionState(): string {
    if (!this.wsConnection) return 'DISCONNECTED';

    switch (this.wsConnection.readyState) {
      case WebSocket.CONNECTING:
        return 'CONNECTING';
      case WebSocket.OPEN:
        return 'OPEN';
      case WebSocket.CLOSING:
        return 'CLOSING';
      case WebSocket.CLOSED:
        return 'CLOSED';
      default:
        return 'UNKNOWN';
    }
  }
}

export const autocompleteService = new AutocompleteService();
